import { _decorator, Color, Component, math, MotionStreak, Node, Sprite, v2, Vec2, Vec3 } from 'cc';
import { PoolManager } from './PoolManager';
import { FallItemManager } from './FallItemManager';
import { CycleItemManager } from './CycleItemManager';
import { EventManager, MyEvent } from './EventManager';
const { ccclass, property } = _decorator;

@ccclass('CycleItem')
export class CycleItem extends Component {
    @property(Sprite)
    public Icon: Sprite = null;

    @property(MotionStreak)
    MotionStreak: MotionStreak = null;

    private _speed: number;
    // private _velocity: Vec2 = Vec2.ZERO;
    private _startY: number = 0;
    private _gravity: number = 0;
    private _freeY: number = 0;
    private _minY: number = 0;
    private _maxY: number = 0;
    private _isFlee: boolean = false;
    private _isPause: boolean = false;

    init(parent: Node, worldPos: Vec3, speed: number, gravity: number, freeY: number, minY: number, maxY: number) {
        this.node.setParent(parent);
        this.node.setWorldPosition(worldPos);
        this._speed = speed;
        this._gravity = gravity;
        this._freeY = freeY;
        this._minY = minY;
        this._maxY = maxY;

        this._isFlee = false;
        //设置颜色
        var color: Color = this.getRandomColor();
        this.Icon.color = color
        this.MotionStreak.color = color;

        let randomY = Math.random() * -0.5 - 0.5; // -1 到 1 之间的随机数，表示向左或向右

        this._startY = randomY * speed;

    }

    protected update(dt: number): void {
        if (this._isPause) return;
        this._startY += dt * this._gravity;
        const nextPos: Vec3 = this.node.getWorldPosition().add3f(0, this._startY * dt, 0);
        // const y: number = this.node.getWorldPosition().y;
        if (nextPos.y < this._minY) {
            CycleItemManager.Instance.removeItem(this.node);
            return;
        }
        else if (!this._isFlee && nextPos.y < this._freeY) {
            if (CycleItemManager.Instance.checkPos(nextPos.x)) {
                CycleItemManager.Instance.addItems(3);
                this._isFlee = true;
                return;
            }
            nextPos.y = this._freeY;
            this._startY *= -1;
        } else if (nextPos.y > this._maxY) {
            nextPos.y = this._maxY;
            this._startY *= -1;
        }
        this.node.setWorldPosition(nextPos);
    }

    // 生成一个随机的 cc.Color
    getRandomColor(): Color {
        let r = Math.floor(Math.random() * 256);
        let g = Math.floor(Math.random() * 256);
        let b = Math.floor(Math.random() * 256);
        return new Color(r, g, b, 255);
    }

    private pause() {
        this._isPause = !this._isPause;
    }

    protected onEnable(): void {
        EventManager.on(MyEvent.PAUSE, this.pause, this);
    }

    protected onDisable(): void {
        EventManager.off(MyEvent.PAUSE, this.pause, this);
    }

}


